package cn.smbms.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.mysql.jdbc.StringUtils;

import cn.smbms.pojo.Provider;
import cn.smbms.service.ProviderService;
import cn.smbms.service.impl.ProviderServiceImpl;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;

@Controller
@RequestMapping("/provider")
public class ProviderController {
	private Logger logger = Logger.getLogger(ProviderController.class);
	@Resource
	private ProviderService providerService;
	/**
	 * 跳转供应商列表
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/providerList.html")
	public String getProviderList(Model model,
			@RequestParam(value = "queryProName",required = false)String queryProName,
			@RequestParam(value = "queryProCode",required = false)String queryProCode,
			@RequestParam(value = "pageIndex",required = false)String pageIndex) throws Exception {
		logger.debug("providerList==========");
		//设置页面容量
    	int pageSize = Constants.pageSize;
    	//当前页码
		int currentPageNo = 1;
		if(StringUtils.isNullOrEmpty(queryProName)){
			queryProName = "";
		}
		if(StringUtils.isNullOrEmpty(queryProCode)){
			queryProCode = "";
		}
		if(pageIndex != null){
    		try{
    			currentPageNo = Integer.valueOf(pageIndex);
    		}catch(NumberFormatException e){
    			return "redirect:/user/syerror.html";
    		}
    	}
		//总数量（表）	
    	int totalCount	= providerService.getProviderCount(queryProName, queryProCode);
    	//总页数
    	PageSupport pages=new PageSupport();
    	pages.setCurrentPageNo(currentPageNo);
    	pages.setPageSize(pageSize);
    	pages.setTotalCount(totalCount);
    	int totalPageCount = pages.getTotalPageCount();
    	//控制首页和尾页
    	if(currentPageNo < 1){
    		currentPageNo = 1;
    	}else if(currentPageNo > totalPageCount){
    		currentPageNo = totalPageCount;
    	}
    	System.out.println(currentPageNo+"currentPageNo"+pageSize+"pageSize");
		List<Provider> providerList = new ArrayList<Provider>();
		providerList = providerService.getProviderList(queryProName,queryProCode,currentPageNo,pageSize);
		model.addAttribute("providerList", providerList);
		model.addAttribute("queryProName", queryProName);
		model.addAttribute("queryProCode", queryProCode);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("currentPageNo", currentPageNo);
		model.addAttribute("providerList", providerList);
		
	 
		return "providerlist.jsp";
	}
	
	/**
	 * 跳转到供应商添加页面
	 * @return
	 */
	@RequestMapping("/providerAdd.html")
	public String addProvider(@ModelAttribute Provider provider) {
		return "provideradd.jsp";
		
	}
}
